<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>React Hooks学习：优势及使用 - smartzheng</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">


<meta name="author" content="smartzheng" /><meta name="description" content="Hooks 是React的一次革命性升级，本文将对其优势和API进行比较全面的解析 为什么要有hooks 在没有hooks之前，除了对于一些无状态组件可以" /><meta name="keywords" content="Hugo, theme, even" />






<meta name="generator" content="Hugo 0.68.3 with theme even" />


<link rel="canonical" href="https://smartzheng.github.io/post/react-hooks%E5%AD%A6%E4%B9%A0%E4%BC%98%E5%8A%BF%E5%8F%8A%E4%BD%BF%E7%94%A8/" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">


<link href="/dist/even.c2a46f00.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.css" integrity="sha256-7TyXnr2YU040zfSP+rEcz29ggW4j56/ujTPwjMzyqFY=" crossorigin="anonymous">


<meta property="og:title" content="React Hooks学习：优势及使用" />
<meta property="og:description" content="Hooks 是React的一次革命性升级，本文将对其优势和API进行比较全面的解析 为什么要有hooks 在没有hooks之前，除了对于一些无状态组件可以" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://smartzheng.github.io/post/react-hooks%E5%AD%A6%E4%B9%A0%E4%BC%98%E5%8A%BF%E5%8F%8A%E4%BD%BF%E7%94%A8/" />
<meta property="article:published_time" content="2019-08-15T00:00:00+00:00" />
<meta property="article:modified_time" content="2019-08-15T00:00:00+00:00" />
<meta itemprop="name" content="React Hooks学习：优势及使用">
<meta itemprop="description" content="Hooks 是React的一次革命性升级，本文将对其优势和API进行比较全面的解析 为什么要有hooks 在没有hooks之前，除了对于一些无状态组件可以">
<meta itemprop="datePublished" content="2019-08-15T00:00:00&#43;00:00" />
<meta itemprop="dateModified" content="2019-08-15T00:00:00&#43;00:00" />
<meta itemprop="wordCount" content="5303">



<meta itemprop="keywords" content="React," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="React Hooks学习：优势及使用"/>
<meta name="twitter:description" content="Hooks 是React的一次革命性升级，本文将对其优势和API进行比较全面的解析 为什么要有hooks 在没有hooks之前，除了对于一些无状态组件可以"/>

<!--[if lte IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
  <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->

</head>
<body>
  <div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/" class="logo">smartzheng</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>
<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    <a href="/">
        <li class="mobile-menu-item">Home</li>
      </a><a href="/post/">
        <li class="mobile-menu-item">Archives</li>
      </a><a href="/tags/">
        <li class="mobile-menu-item">Tags</li>
      </a><a href="/categories/">
        <li class="mobile-menu-item">Categories</li>
      </a>
  </ul>
</nav>
  <div class="container" id="mobile-panel">
    <header id="header" class="header">
        <div class="logo-wrapper">
  <a href="/" class="logo">smartzheng</a>
</div>

<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
        <a class="menu-item-link" href="/">Home</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/post/">Archives</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/tags/">Tags</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/categories/">Categories</a>
      </li>
  </ul>
</nav>
    </header>

    <main id="main" class="main">
      <div class="content-wrapper">
        <div id="content" class="content">
          <article class="post">
    
    <header class="post-header">
      <h1 class="post-title">React Hooks学习：优势及使用</h1>

      <div class="post-meta">
        <span class="post-time"> 2019-08-15 </span>
        <div class="post-category">
            <a href="/categories/web%E5%89%8D%E7%AB%AF/"> web前端 </a>
            </div>
        
      </div>
    </header>

    <div class="post-toc" id="post-toc">
  <h2 class="post-toc-title">文章目录</h2>
  <div class="post-toc-content always-active">
    <nav id="TableOfContents">
  <ul>
    <li><a href="#为什么要有hooks">为什么要有hooks</a></li>
    <li><a href="#使用hooks">使用hooks</a>
      <ul>
        <li><a href="#usestate">useState</a></li>
        <li><a href="#useeffect">useEffect</a></li>
        <li><a href="#usecontext">useContext</a></li>
        <li><a href="#usememousecallback">useMemo&amp;useCallback</a></li>
        <li><a href="#useref">useRef</a></li>
        <li><a href="#自定义hooks">自定义Hooks</a></li>
      </ul>
    </li>
  </ul>
</nav>
  </div>
</div>
    <div class="post-content">
      <p><em><strong>Hooks 是React的一次革命性升级，本文将对其优势和API进行比较全面的解析</strong></em></p>
<h2 id="为什么要有hooks">为什么要有hooks</h2>
<p>在没有hooks之前，除了对于一些无状态组件可以使用函数来声明组件以外，大家都会使用class来声明组件。作为一个主要工作内容为Android开发的我，早已习惯万物皆class，而Android中的Activity（可以理解为每一个交互界面）就是class，所以也欣然接受，并且在ES6中class带有的constructor、super以及react的生命周期函数对使用Java的Android开发者来讲很容易理解接受。</p>
<p>但是使用class来声明组件却存在以下问题：</p>
<ol>
<li>状态逻辑难以复用<br>
假如有一段逻辑代码需要在多个组件中使用，那么在以前，可以通过以下几个方式来实现：</li>
</ol>
<ul>
<li>copy代码，显然不符合代码设计的原则</li>
<li>继承，一方面，js只支持单继承（Java中可以通过接口实现对多个类的实现），想要对复用多个组件的逻辑就无能为力；另一方面，只为了复用部- 分逻辑而滥用继承，显然是违背oop原则的</li>
<li>HOC高阶组件，使用HOC复用的原理很简单，就是包裹封装，比如我们想实现对onScroll方法的复用：</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kr">import</span> <span class="nx">React</span><span class="p">,{</span><span class="nx">Component</span><span class="p">}</span> <span class="nx">from</span> <span class="s1">&#39;react&#39;</span>

<span class="kd">function</span> <span class="nx">scrollable</span><span class="p">(</span><span class="nx">Child</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">return</span> <span class="kr">class</span> <span class="nx">ScrollWrapper</span> <span class="kr">extends</span> <span class="nx">Component</span> <span class="p">{</span>
        <span class="nx">ref</span> <span class="o">=</span> <span class="nx">React</span><span class="p">.</span><span class="nx">createRef</span><span class="p">()</span>
        <span class="nx">onScroll</span> <span class="o">=</span> <span class="p">(...</span><span class="nx">args</span><span class="p">)</span> <span class="p">=&gt;</span> <span class="p">{</span>
            <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">&#39;onscroll&#39;</span><span class="p">)</span>
            <span class="k">this</span><span class="p">.</span><span class="nx">ref</span><span class="p">.</span><span class="nx">current</span><span class="p">.</span><span class="nx">onScroll</span><span class="p">(...</span><span class="nx">args</span><span class="p">)</span>
        <span class="p">}</span>
        <span class="nx">componentDidMount</span><span class="p">()</span> <span class="p">{</span>
            <span class="nb">document</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;scroll&#39;</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">onScroll</span><span class="p">,</span> <span class="kc">false</span><span class="p">);</span>
        <span class="p">}</span>

        <span class="nx">componentWillUnmount</span><span class="p">()</span> <span class="p">{</span>
            <span class="nb">document</span><span class="p">.</span><span class="nx">removeEventListener</span><span class="p">(</span><span class="s1">&#39;scroll&#39;</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">onScroll</span><span class="p">,</span> <span class="kc">false</span><span class="p">);</span>
        <span class="p">}</span>

        <span class="nx">render</span><span class="p">()</span> <span class="p">{</span>
            <span class="k">return</span> <span class="o">&lt;</span><span class="nx">Child</span> <span class="nx">ref</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">ref</span><span class="p">}</span> <span class="o">/&gt;</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="kr">class</span> <span class="nx">ScrollableApp</span> <span class="kr">extends</span> <span class="nx">Component</span> <span class="p">{</span>
    <span class="nx">onScroll</span><span class="p">(){</span>
        <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">&#39;child onscroll&#39;</span><span class="p">)</span>
    <span class="p">}</span>
    <span class="nx">render</span><span class="p">()</span> <span class="p">{</span> 
        <span class="k">return</span> <span class="o">&lt;</span><span class="nx">div</span> <span class="nx">style</span><span class="o">=</span><span class="p">{{</span><span class="nx">color</span><span class="o">:</span><span class="s1">&#39;red&#39;</span><span class="p">,</span><span class="nx">height</span><span class="o">:</span><span class="mi">10000</span><span class="p">,</span><span class="nx">width</span><span class="o">:</span><span class="mi">800</span><span class="p">}}</span><span class="o">&gt;</span>
            
        <span class="o">&lt;</span><span class="err">/div&gt;</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="kr">export</span> <span class="k">default</span> <span class="nx">scrollable</span><span class="p">(</span><span class="nx">ScrollableApp</span><span class="p">);</span>

</code></pre></td></tr></table>
</div>
</div><p>ScrollableApp通过高阶组件即函数scrollable()封装后，复用了ScrollWrapper中的onScroll()方法，并且还能再ScrollWrapper的onScroll使子组件ScrollableApp中的onScroll也能得到调用；使用渲染属性也可以实现复用：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kr">export</span> <span class="kr">class</span> <span class="nx">Scrollable</span> <span class="kr">extends</span> <span class="nx">Component</span> <span class="p">{</span>
    <span class="nx">onScroll</span> <span class="o">=</span> <span class="p">(...</span><span class="nx">args</span><span class="p">)</span> <span class="p">=&gt;</span> <span class="p">{</span>
        <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">&#39;onscroll&#39;</span><span class="p">)</span>
        <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">children</span><span class="p">)</span>        
    <span class="p">}</span>
    <span class="nx">componentDidMount</span><span class="p">()</span> <span class="p">{</span>
        <span class="nb">document</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;scroll&#39;</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">onScroll</span><span class="p">,</span> <span class="kc">false</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="nx">componentWillUnmount</span><span class="p">()</span> <span class="p">{</span>
        <span class="nb">document</span><span class="p">.</span><span class="nx">removeEventListener</span><span class="p">(</span><span class="s1">&#39;scroll&#39;</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">onScroll</span><span class="p">,</span> <span class="kc">false</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="nx">render</span><span class="p">()</span> <span class="p">{</span>
        <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">render</span><span class="p">()</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="kr">export</span> <span class="kr">class</span> <span class="nx">ScrollableApp</span> <span class="kr">extends</span> <span class="nx">Component</span> <span class="p">{</span>
    <span class="nx">onScroll</span><span class="p">()</span> <span class="p">{</span>
        <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">&#39;child onscroll&#39;</span><span class="p">)</span>
    <span class="p">}</span>
    <span class="nx">render</span><span class="p">()</span> <span class="p">{</span>
        <span class="k">return</span> <span class="o">&lt;</span><span class="nx">div</span> <span class="nx">style</span><span class="o">=</span><span class="p">{{</span> <span class="nx">color</span><span class="o">:</span> <span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="nx">height</span><span class="o">:</span> <span class="mi">10000</span><span class="p">,</span> <span class="nx">width</span><span class="o">:</span> <span class="mi">800</span> <span class="p">}}</span><span class="o">&gt;</span>

        <span class="o">&lt;</span><span class="err">/div&gt;</span>
    <span class="p">}</span>
<span class="p">}</span>

</code></pre></td></tr></table>
</div>
</div><p>使用时：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span><span class="lnt">9
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">App</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">return</span> <span class="p">(</span>
    <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
      <span class="o">&lt;</span><span class="nx">Scrollable</span> <span class="nx">render</span><span class="o">=</span><span class="p">{()</span> <span class="p">=&gt;</span> <span class="o">&lt;</span><span class="nx">ScrollableApp</span><span class="o">&gt;&lt;</span><span class="err">/ScrollableApp&gt;}&gt;&lt;/Scrollable&gt;</span>
    <span class="o">&lt;</span><span class="err">/div&gt;</span>
  <span class="p">);</span>
<span class="p">}</span>

<span class="kr">export</span> <span class="k">default</span> <span class="nx">App</span><span class="p">;</span>
</code></pre></td></tr></table>
</div>
</div><p>这个方法和高阶组件方式差不多，不再赘述<br>
<em>使用这两者虽然能实现逻辑复用，但无疑对代码的简洁和运行性能都有不少的损耗</em></p>
<ul>
<li>另外，“组合优于继承”，或许可以使用策略模式，抽取出不同的类来封装这些逻辑，在使用时引入相关的类来实现，但这无疑有点过度设计，也大大增加了代码结构的复杂度</li>
</ul>
<ol start="2">
<li>
<p>类组件复杂，难以维护，主要指生命周期函数混乱，比如上面的onScroll监听，在componentDidMount和componentWillUnmount分别要注册反注册，相关的逻辑分散在不同地方，而在componentDidMount往往还需要处理类似网络请求等各种初始化的动作，也导致不相关的逻辑混杂在一起，使得代码难以维护（这个在Android开发中其实也是再正常不过做法&hellip;）</p>
</li>
<li>
<p>this指向等问题<br>
上面有一段代码：</p>
</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="nx">onScroll</span> <span class="o">=</span> <span class="p">(...</span><span class="nx">args</span><span class="p">)</span> <span class="p">=&gt;</span> <span class="p">{</span>
   <span class="p">...</span>
<span class="p">}</span>

</code></pre></td></tr></table>
</div>
</div><p>这里使用类属性的方式定义onScroll，才能通过this.onScroll访问到该方法，而如果声明为类成员函数，则在向下一级组件传递回调函数时无法正确访问到该方法</p>
<p>而hooks则很好的解决了以上的问题</p>
<h2 id="使用hooks">使用hooks</h2>
<h3 id="usestate">useState</h3>
<ol>
<li>使用</li>
</ol>
<p>在没有react hooks之前，组件可以分为有状态组件和无状态组件，如：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kr">class</span> <span class="nx">Counter</span> <span class="kr">extends</span> <span class="nx">Component</span> <span class="p">{</span>
    <span class="nx">state</span> <span class="o">=</span> <span class="p">{</span>
        <span class="nx">count</span><span class="o">:</span> <span class="mi">0</span>
    <span class="p">}</span>
    <span class="nx">render</span><span class="p">()</span> <span class="p">{</span>
        <span class="k">return</span> <span class="p">(</span>
            <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
                <span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">count</span><span class="p">}</span>
            <span class="o">&lt;</span><span class="err">/div&gt;</span>
        <span class="p">)</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">Counter</span><span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">return</span> <span class="p">(</span>
        <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
            <span class="p">{</span><span class="nx">props</span><span class="p">.</span><span class="nx">count</span><span class="p">}</span>
        <span class="o">&lt;</span><span class="err">/div&gt;</span>
    <span class="p">)</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>第一种写法Counter中存储了状态state，而函数组件写法中只能通过props来获取状态</p>
<p>使用useState：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kr">import</span> <span class="nx">React</span><span class="p">,</span> <span class="p">{</span> <span class="nx">useState</span> <span class="p">}</span> <span class="nx">from</span> <span class="s1">&#39;react&#39;</span>

<span class="kr">export</span> <span class="k">default</span> <span class="kd">function</span> <span class="nx">Counter</span><span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="p">{</span>
    <span class="kr">const</span> <span class="p">[</span><span class="nx">count</span><span class="p">,</span> <span class="nx">setCount</span><span class="p">]</span> <span class="o">=</span> <span class="nx">useState</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="p">(</span>
        <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
            <span class="o">&lt;</span><span class="nx">button</span>
                <span class="nx">onClick</span><span class="o">=</span><span class="p">{()</span> <span class="p">=&gt;</span> <span class="p">{</span>
                    <span class="nx">setCount</span><span class="p">(</span><span class="nx">count</span><span class="p">=&gt;</span><span class="nx">count</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
                <span class="p">}}</span><span class="o">&gt;</span>
            <span class="o">&lt;</span><span class="err">/button&gt;</span>
            <span class="p">{</span><span class="nx">count</span><span class="p">}</span>
        <span class="o">&lt;</span><span class="err">/div&gt;</span>
    <span class="p">)</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>这里<code>const [count, setCount] = useState(0)</code>中，相当于定义了一个count变量作为该组件state的一个属性，而useState中传入的值为count的初始默认值（也可以不传入，则为undefined），setCount为改变count值的方法；以上代码等价于：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kr">export</span> <span class="kr">class</span> <span class="nx">Counter</span> <span class="kr">extends</span> <span class="nx">React</span><span class="p">.</span><span class="nx">Component</span> <span class="p">{</span>
    <span class="nx">state</span> <span class="o">=</span> <span class="p">{</span>
        <span class="nx">count</span><span class="o">:</span> <span class="mi">0</span>
    <span class="p">}</span>
    <span class="nx">render</span><span class="p">()</span> <span class="p">{</span>
        <span class="k">return</span> <span class="p">(</span>
            <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
                <span class="o">&lt;</span><span class="nx">button</span>
                    <span class="nx">onClick</span><span class="o">=</span><span class="p">{()</span> <span class="p">=&gt;</span> <span class="p">{</span>
                        <span class="k">this</span><span class="p">.</span><span class="nx">setState</span><span class="p">(</span>
                            <span class="p">{</span>
                                <span class="nx">count</span><span class="o">:</span> <span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">count</span> <span class="o">+</span> <span class="mi">1</span>
                            <span class="p">}</span>
                        <span class="p">)</span>
                    <span class="p">}}</span><span class="o">&gt;</span>
                <span class="o">&lt;</span><span class="err">/button&gt;</span>
                <span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">count</span><span class="p">}</span>
            <span class="o">&lt;</span><span class="err">/div&gt;</span>
        <span class="p">)</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p><em>可见，使用useState使得代码大大简化，可以不使用class声明组件，也不用担心this指向的问题；并且从此我们不用再以有无状态来区分组件了，因为函数组件也可以拥有状态</em></p>
<p>2.原理<br>
这里有几个值得探讨的问题：</p>
<ul>
<li>
<p>useState()如何确定应该返回的是哪一个component的state<br>
这个很简单，因为js运行在单线程环境中，所以在运行到某一个useState函数时，可以获取到对应的运行上下文处在哪一个component中</p>
</li>
<li>
<p>如何确定useState对应于哪一个返回值<br>
思考以下的伪代码：</p>
</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">Counter</span><span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="nx">someCondition</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">useState</span><span class="p">();</span>
  <span class="p">}</span>
  <span class="nx">useState</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>在实际执行中会报错，而且如果eslint配置了react-hooks/rules-of-hooks，会直接编译报错<br>
实际上为了代码尽可能简洁，useState是通过记录第一次运行时的顺序来确定之后的每次运行分别返回对应哪个state的，所以<em><strong>Hooks函数必须始终以相同的次序和数量被调用</strong></em></p>
<ul>
<li>setState相同值的时候会否重新渲染<br>
改写之前的代码，setCount时每次都为0，发现并不会执行render函数</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">function Counter(props) {
    const [count, setCount] = useState(0)
    console.log(&#39;render&#39;)
    return (
        &lt;div&gt;
            &lt;button
                onClick={() =&gt; {
                    setCount(0)
                }}&gt;
            &lt;/button&gt;
            {count}
        &lt;/div&gt;
    )
}
</code></pre></td></tr></table>
</div>
</div><p>假如我们的state中存储的是对象呢？</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">Counter</span><span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="p">{</span>
    <span class="kr">const</span> <span class="p">[</span><span class="nx">countObj</span><span class="p">,</span> <span class="nx">setCountObj</span><span class="p">]</span> <span class="o">=</span> <span class="nx">useState</span><span class="p">({</span> <span class="nx">count</span><span class="o">:</span> <span class="mi">0</span> <span class="p">})</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">&#39;render&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="p">(</span>
        <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
            <span class="o">&lt;</span><span class="nx">button</span>
                <span class="nx">onClick</span><span class="o">=</span><span class="p">{()</span> <span class="p">=&gt;</span> <span class="p">{</span>
                    <span class="nx">countObj</span><span class="p">.</span><span class="nx">count</span> <span class="o">=</span> <span class="nx">countObj</span><span class="p">.</span><span class="nx">count</span> <span class="o">+</span> <span class="mi">1</span>
                    <span class="nx">setCountObj</span><span class="p">(</span><span class="nx">countObj</span><span class="p">)</span>
                <span class="p">}}</span><span class="o">&gt;</span>
            <span class="o">&lt;</span><span class="err">/button&gt;</span>
            <span class="p">{</span><span class="nx">countObj</span><span class="p">.</span><span class="nx">count</span><span class="p">}</span>
        <span class="o">&lt;</span><span class="err">/div&gt;</span>
    <span class="p">)</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>点击button，发现也未重新渲染。因此在setState时，如果为对象，对比的地址值未改变，并不会重新render，这和PureComponent类似</p>
<h3 id="useeffect">useEffect</h3>
<p>effec被翻译过来为副作用，但是这个确很容易产生语义误解；实际上副作用实际上指的是视图组件与视图组件之外系统进行交互的行为u，比如与DOM交互，网络请求，数据持久化操作等<br>
假如我们需要在componentDidMount之后设置onScroll监听，使用class的写法为：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kr">class</span> <span class="nx">Scrollable</span> <span class="kr">extends</span> <span class="nx">React</span><span class="p">.</span><span class="nx">Component</span> <span class="p">{</span>
    <span class="nx">onScroll</span> <span class="o">=</span> <span class="p">()</span> <span class="p">=&gt;</span> <span class="p">{</span>
        <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">&#39;onscroll&#39;</span><span class="p">)</span>
    <span class="p">}</span>
    <span class="nx">componentDidMount</span><span class="p">()</span> <span class="p">{</span>
        <span class="nb">document</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;scroll&#39;</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">onScroll</span><span class="p">,</span> <span class="kc">false</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>通过useEffect改写则为：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">Scrollable</span><span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">useEffect</span><span class="p">(()</span> <span class="p">=&gt;</span> <span class="p">{</span>
        <span class="nb">document</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;scroll&#39;</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">onScroll</span><span class="p">,</span> <span class="kc">false</span><span class="p">);</span>
    <span class="p">})</span>
    <span class="k">return</span> <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;&lt;</span><span class="err">/div&gt;</span>
<span class="p">}</span>

</code></pre></td></tr></table>
</div>
</div><p>useEffect()中的函数会在每次componentDidMount、componentDidUpdate的时候执行，如果要在componentWillUnmount中取消监听也很简单，只需在useEffect()传入的函数中return相关处理函数即可：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">Scrollable</span><span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">useEffect</span><span class="p">(()</span> <span class="p">=&gt;</span> <span class="p">{</span>
        <span class="nb">document</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;scroll&#39;</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">onScroll</span><span class="p">,</span> <span class="kc">false</span><span class="p">);</span>
        <span class="k">return</span> <span class="p">()</span> <span class="p">=&gt;</span> <span class="p">{</span>
            <span class="nb">document</span><span class="p">.</span><span class="nx">removeEventListener</span><span class="p">(</span><span class="s1">&#39;scroll&#39;</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">onScroll</span><span class="p">,</span> <span class="kc">false</span><span class="p">);</span>
        <span class="p">};</span>
    <span class="p">})</span>
    <span class="k">return</span> <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;&lt;</span><span class="err">/div&gt;</span>
<span class="p">}</span>

</code></pre></td></tr></table>
</div>
</div><p>除此之外，useEffect还可以传入第二个参数，该参数类型为数组；这里分为三种情况：</p>
<p>1.不传入数组参数：在不传入该数组的情况下（参考上面的代码），每次componentDidMount、componentDidUpdate或componentWillUnmount时都会执行对应的副作用函数</p>
<p>2.传入空数组：该副作用会在组件整个生命周期中只执行一次、清理一次；这很适用于对网络请求、事件监听等操作</p>
<p>3.传入非空数组：该副作用会在数组中的各个参数发生变化时（对象比较地址值），才会在对应的生命周期中重新执行</p>
<p>通过useEffect，可以使得我们的代码更简洁，逻辑更清晰易维护，对数组参数的控制也能帮助我们更轻松的写出高性能的代码</p>
<h3 id="usecontext">useContext</h3>
<p>在没有hooks之前Context就已经存在，用以实现跨层级数据传递，一般使用Consumer和ContextType实现</p>
<p>但是Context的似乎使用得不是很多，多数还是通过redux的store存储全局数据；useContext使得Context的使用更容易，可以在函数组件中使用Context，并且不用依赖ContextType，避免了每一个组件只能对应一个ContextType的缺点，当然也不需要Consumer</p>
<p>使用很简单（这里只是演示，代码结构可以根据实际做优化；这里顺便列出以往使用Consumer和ContextType实现Context数据传递的写法作对比）：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span><span class="lnt">43
</span><span class="lnt">44
</span><span class="lnt">45
</span><span class="lnt">46
</span><span class="lnt">47
</span><span class="lnt">48
</span><span class="lnt">49
</span><span class="lnt">50
</span><span class="lnt">51
</span><span class="lnt">52
</span><span class="lnt">53
</span><span class="lnt">54
</span><span class="lnt">55
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kr">import</span> <span class="nx">React</span><span class="p">,</span> <span class="p">{</span> <span class="nx">Component</span><span class="p">,</span> <span class="nx">createContext</span><span class="p">,</span> <span class="nx">useContext</span><span class="p">,</span> <span class="nx">useState</span> <span class="p">}</span> <span class="nx">from</span> <span class="s1">&#39;react&#39;</span>
<span class="kr">const</span> <span class="nx">CountContext</span> <span class="o">=</span> <span class="nx">createContext</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>

<span class="kd">function</span> <span class="nx">App</span><span class="p">()</span> <span class="p">{</span>
  <span class="kr">const</span> <span class="p">[</span><span class="nx">count</span><span class="p">,</span> <span class="nx">setCount</span><span class="p">]</span> <span class="o">=</span> <span class="nx">useState</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
  <span class="k">return</span> <span class="p">(</span>
    <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
      <span class="o">&lt;</span><span class="nx">button</span>
        <span class="nx">onClick</span><span class="o">=</span><span class="p">{()</span> <span class="p">=&gt;</span> <span class="p">{</span>
          <span class="nx">setCount</span><span class="p">(</span><span class="nx">count</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
        <span class="p">}}</span><span class="o">&gt;</span>
      <span class="o">&lt;</span><span class="err">/button&gt;</span>
      <span class="o">&lt;</span><span class="nx">CountContext</span><span class="p">.</span><span class="nx">Provider</span> <span class="nx">value</span><span class="o">=</span><span class="p">{</span><span class="nx">count</span><span class="p">}</span><span class="o">&gt;</span>
        <span class="o">&lt;</span><span class="nx">CounterByConsummer</span><span class="o">&gt;&lt;</span><span class="err">/CounterByConsummer&gt;</span>
        <span class="o">&lt;</span><span class="nx">Counter</span><span class="o">&gt;&lt;</span><span class="err">/Counter&gt;</span>
        <span class="o">&lt;</span><span class="nx">CounterByContextType</span><span class="o">&gt;&lt;</span><span class="err">/CounterByContextType&gt;</span>
      <span class="o">&lt;</span><span class="err">/CountContext.Provider&gt;</span>
    <span class="o">&lt;</span><span class="err">/div&gt;</span>
  <span class="p">);</span>
<span class="p">}</span>

<span class="c1">//useContext写法
</span><span class="c1"></span><span class="kd">function</span> <span class="nx">Counter</span><span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="p">{</span>
  <span class="kr">const</span> <span class="nx">count</span> <span class="o">=</span> <span class="nx">useContext</span><span class="p">(</span><span class="nx">CountContext</span><span class="p">)</span>
  <span class="k">return</span> <span class="p">(</span>
    <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
      <span class="p">{</span><span class="nx">count</span><span class="p">}</span>
    <span class="o">&lt;</span><span class="err">/div&gt;</span>
  <span class="p">)</span>
<span class="p">}</span>
<span class="c1">//Consummer写法
</span><span class="c1"></span><span class="kr">class</span> <span class="nx">CounterByConsummer</span> <span class="kr">extends</span> <span class="nx">Component</span> <span class="p">{</span>
  <span class="nx">render</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">return</span> <span class="p">(</span>
      <span class="o">&lt;</span><span class="nx">CountContext</span><span class="p">.</span><span class="nx">Consumer</span><span class="o">&gt;</span>
        <span class="p">{</span><span class="nx">count</span> <span class="p">=&gt;</span> <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span><span class="p">{</span><span class="nx">count</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/div&gt;}</span>
      <span class="o">&lt;</span><span class="err">/CountContext.Consumer&gt;</span>
    <span class="p">)</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="c1">//ContextType写法
</span><span class="c1"></span><span class="kr">class</span> <span class="nx">CounterByContextType</span> <span class="kr">extends</span> <span class="nx">Component</span> <span class="p">{</span>
  <span class="kr">static</span> <span class="nx">contextType</span> <span class="o">=</span> <span class="nx">CountContext</span>
  <span class="nx">render</span><span class="p">()</span> <span class="p">{</span>
    <span class="kr">const</span> <span class="nx">count</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">context</span>
    <span class="k">return</span> <span class="p">(</span>
      <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
        <span class="p">{</span><span class="nx">count</span><span class="p">}</span>
      <span class="o">&lt;</span><span class="err">/div&gt;</span>
    <span class="p">)</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="kr">export</span> <span class="k">default</span> <span class="nx">App</span><span class="p">;</span>
</code></pre></td></tr></table>
</div>
</div><p>需要注意的一点是，不要滥用context，因为会破坏组件的独立性</p>
<h3 id="usememousecallback">useMemo&amp;useCallback</h3>
<h4 id="理解memo">理解memo</h4>
<p>为了提高react的运行效率，避免无用的重渲染，我们常使用继承PureComponent的方式；而在函数组件则可以使用<code>React.memo(Component)</code>来达到同样的效果；</p>
<h4 id="使用usememo">使用useMemo</h4>
<p>React.memo()针对组件，而useMemo则是针对组件的方法，思考如下代码：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kr">import</span> <span class="nx">React</span><span class="p">,</span> <span class="p">{</span> <span class="nx">useMemo</span><span class="p">,</span> <span class="nx">useState</span> <span class="p">}</span> <span class="nx">from</span> <span class="s1">&#39;react&#39;</span>

<span class="kd">function</span> <span class="nx">App</span><span class="p">()</span> <span class="p">{</span>
  <span class="kr">const</span> <span class="p">[</span><span class="nx">name</span><span class="p">,</span> <span class="nx">setName</span><span class="p">]</span> <span class="o">=</span> <span class="nx">useState</span><span class="p">(</span><span class="s1">&#39;smartzheng&#39;</span><span class="p">)</span>
  <span class="kr">const</span> <span class="p">[</span><span class="nx">age</span><span class="p">,</span> <span class="nx">setAge</span><span class="p">]</span> <span class="o">=</span> <span class="nx">useState</span><span class="p">(</span><span class="mi">18</span><span class="p">)</span>
  <span class="k">return</span> <span class="p">(</span>
    <span class="o">&lt;&gt;</span>
      <span class="o">&lt;</span><span class="nx">button</span>
        <span class="nx">onClick</span><span class="o">=</span><span class="p">{()</span> <span class="p">=&gt;</span> <span class="p">{</span>
          <span class="nx">setName</span><span class="p">(</span><span class="nx">name</span> <span class="o">+</span> <span class="s1">&#39;changed&#39;</span><span class="p">)</span>
        <span class="p">}}</span><span class="o">&gt;</span>
        <span class="nx">changeName</span>
      <span class="o">&lt;</span><span class="err">/button&gt;</span>
      <span class="o">&lt;</span><span class="nx">button</span>
        <span class="nx">onClick</span><span class="o">=</span><span class="p">{()</span> <span class="p">=&gt;</span> <span class="p">{</span>
          <span class="nx">setAge</span><span class="p">(</span><span class="nx">age</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
        <span class="p">}}</span><span class="o">&gt;</span>
        <span class="nx">changeAge</span>
      <span class="o">&lt;</span><span class="err">/button&gt;</span>
      <span class="o">&lt;</span><span class="nx">Description</span> <span class="nx">age</span><span class="o">=</span><span class="p">{</span><span class="nx">age</span><span class="p">}</span> <span class="nx">name</span><span class="o">=</span><span class="p">{</span><span class="nx">name</span><span class="p">}</span><span class="o">&gt;&lt;</span><span class="err">/Description&gt;</span>
    <span class="o">&lt;</span><span class="err">/&gt;</span>
  <span class="p">);</span>
<span class="p">}</span>


<span class="kd">function</span> <span class="nx">Description</span><span class="p">({</span> <span class="nx">name</span><span class="p">,</span> <span class="nx">age</span> <span class="p">})</span> <span class="p">{</span>
  <span class="kd">function</span> <span class="nx">getAge</span><span class="p">(</span><span class="nx">age</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">&#39;changeAge&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="nx">age</span> <span class="o">+</span> <span class="s1">&#39;岁&#39;</span>
  <span class="p">}</span>
  <span class="kr">const</span> <span class="nx">newAge</span> <span class="o">=</span> <span class="nx">useMemo</span><span class="p">(()</span> <span class="p">=&gt;</span> <span class="nx">getAge</span><span class="p">(</span><span class="nx">age</span><span class="p">),</span> <span class="p">[</span><span class="nx">age</span><span class="p">])</span>

  <span class="k">return</span> <span class="o">&lt;&gt;</span>
    <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
      <span class="p">{</span><span class="nx">name</span><span class="p">}</span>
    <span class="o">&lt;</span><span class="err">/div&gt;</span>
    <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
      <span class="p">{</span><span class="nx">newAge</span><span class="p">}</span>
    <span class="o">&lt;</span><span class="sr">/div&gt;&lt;/</span><span class="o">&gt;</span>
<span class="p">}</span>
<span class="kr">export</span> <span class="k">default</span> <span class="nx">App</span><span class="p">;</span>

</code></pre></td></tr></table>
</div>
</div><p>这段代码主要做的是显示两个button，一个用来改变name，一个改变age，而子组件中对name和age进行显示，并且通过getAge()在age后加上“岁”字。测试发现，点击changeName和changeAge都会导致子组件重新执行getAge()，这并不是我们想要的结果；这里就可以通过useMemo来实现只有在age发生变化时才执行getAge()，使用很简单，只需将 <code>const newAge = useMemo(() =&gt; getAge(age), [age])</code> 改为<code>const newAge = useMemo(() =&gt; getAge(age), [age])</code>即可</p>
<p>在<code>useMemo(() =&gt; getAge(age), [age])</code>中，传入的是一个函数，可以理解为一个回调，数组<code>[age]</code>代表该回调只有在age变化时才会执行，而执行的内容为<code>getAge(age)</code></p>
<h4 id="使用usecallback">使用useCallback</h4>
<p>useCallback和useMemo很类似，不过他返回的是缓存的函数：<code>const fnA = useCallback(fnB, [a])</code>，代表useCallback会将fnB函数返回，返回值是否改变依赖于a值是否改变。举例如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kr">import</span> <span class="nx">React</span><span class="p">,</span> <span class="p">{</span> <span class="nx">useState</span><span class="p">,</span> <span class="nx">useCallback</span> <span class="p">}</span> <span class="nx">from</span> <span class="s1">&#39;react&#39;</span><span class="p">;</span>
<span class="kr">const</span> <span class="nx">set</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Set</span><span class="p">();</span>

<span class="kr">export</span> <span class="k">default</span> <span class="kd">function</span> <span class="nx">Callback</span><span class="p">()</span> <span class="p">{</span>
  <span class="kr">const</span> <span class="p">[</span><span class="nx">count</span><span class="p">,</span> <span class="nx">setCount</span><span class="p">]</span> <span class="o">=</span> <span class="nx">useState</span><span class="p">(</span><span class="mi">0</span><span class="p">);</span>
  <span class="kr">const</span> <span class="p">[</span><span class="nx">val</span><span class="p">,</span> <span class="nx">setVal</span><span class="p">]</span> <span class="o">=</span> <span class="nx">useState</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">);</span>

  <span class="kr">const</span> <span class="nx">callback</span> <span class="o">=</span> <span class="nx">useCallback</span><span class="p">(()</span> <span class="p">=&gt;</span> <span class="p">{</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">count</span><span class="p">);</span>
  <span class="p">},</span> <span class="p">[</span><span class="nx">count</span><span class="p">]);</span>
  <span class="nx">set</span><span class="p">.</span><span class="nx">add</span><span class="p">(</span><span class="nx">callback</span><span class="p">);</span>
  <span class="k">return</span> <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
    <span class="o">&lt;</span><span class="nx">h1</span><span class="o">&gt;</span><span class="p">{</span><span class="nx">count</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/h1&gt;</span>
    <span class="o">&lt;</span><span class="nx">h1</span><span class="o">&gt;</span><span class="p">{</span><span class="nx">set</span><span class="p">.</span><span class="nx">size</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/h1&gt;</span>
    <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
      <span class="o">&lt;</span><span class="nx">button</span> <span class="nx">onClick</span><span class="o">=</span><span class="p">{()</span> <span class="p">=&gt;</span> <span class="nx">setCount</span><span class="p">(</span><span class="nx">count</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)}</span><span class="o">&gt;</span><span class="nx">changeCount</span><span class="o">&lt;</span><span class="err">/button&gt;</span>
      <span class="o">&lt;</span><span class="nx">input</span> <span class="nx">value</span><span class="o">=</span><span class="p">{</span><span class="nx">val</span><span class="p">}</span> <span class="nx">onChange</span><span class="o">=</span><span class="p">{</span><span class="nx">event</span> <span class="p">=&gt;</span> <span class="nx">setVal</span><span class="p">(</span><span class="nx">event</span><span class="p">.</span><span class="nx">target</span><span class="p">.</span><span class="nx">value</span><span class="p">)}</span> <span class="o">/&gt;</span>
    <span class="o">&lt;</span><span class="err">/div&gt;</span>
  <span class="o">&lt;</span><span class="err">/div&gt;;</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>这里的callback就是对<code>() =&gt; {console.log(count)</code>的缓存，通过一个set来存放它，只有当点击changeCount的按钮是set的size才会发生变化，说明只有在count变化时，才会返回新的callback方法，这对减少重复创建相同的方法对象很有帮助</p>
<h3 id="useref">useRef</h3>
<p>在hooks之前，常用createRef来创建ref来获取DOM元素的引用，React Hooks中则提供了useRef</p>
<ol>
<li>使用useRef获取DOM元素的引用</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kr">import</span> <span class="nx">React</span><span class="p">,</span> <span class="p">{</span> <span class="nx">PureComponent</span><span class="p">,</span> <span class="nx">useRef</span> <span class="p">}</span> <span class="nx">from</span> <span class="s1">&#39;react&#39;</span><span class="p">;</span>

<span class="kd">function</span> <span class="nx">App</span><span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="p">{</span>
  <span class="kr">const</span> <span class="nx">countRef</span> <span class="o">=</span> <span class="nx">useRef</span><span class="p">();</span>
  <span class="k">return</span> <span class="p">(</span>
    <span class="o">&lt;&gt;</span>
      <span class="o">&lt;</span><span class="nx">Counter</span> <span class="nx">ref</span><span class="o">=</span><span class="p">{</span><span class="nx">countRef</span><span class="p">}</span><span class="o">&gt;&lt;</span><span class="err">/Counter&gt;</span>
      <span class="o">&lt;</span><span class="nx">button</span> <span class="nx">onClick</span><span class="o">=</span><span class="p">{()</span> <span class="p">=&gt;</span> <span class="p">{</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">countRef</span><span class="p">.</span><span class="nx">current</span><span class="p">)</span> <span class="p">}}</span><span class="o">&gt;&lt;</span><span class="err">/button&gt;</span>
    <span class="o">&lt;</span><span class="err">/&gt;</span>
  <span class="p">)</span>
<span class="p">}</span>

<span class="kr">class</span> <span class="nx">Counter</span> <span class="kr">extends</span> <span class="nx">PureComponent</span> <span class="p">{</span>
  <span class="nx">render</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">return</span> <span class="p">(</span>
      <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>

      <span class="o">&lt;</span><span class="err">/div&gt;</span>
    <span class="p">)</span>
  <span class="p">}</span>
<span class="p">}</span>
<span class="kr">export</span> <span class="k">default</span> <span class="nx">App</span>
</code></pre></td></tr></table>
</div>
</div><p>在上述代码中，通过useRef()创建了countRef并在Counter组件上进行赋值，点击button，每次都会正确打印出Counter组件<br>
值得注意的是，这里的Counter如果使用函数组件则会报错，提示<code>function components can not be given refs</code>，原因是函数组件会被React底层处理，被class wrap，所以直接给该函数组件进行ref赋值没有意义；从这里也可以发现函数组件还不能完全替代类组件</p>
<ol start="2">
<li>使用useRef存储对象
正常情况下，如果在函数组件中声明一个变量，那么该变量会在每次渲染时重新创建，而使用useRef可以实现跨越声明周期存储数据，思考如下代码：</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kr">import</span> <span class="nx">React</span><span class="p">,</span> <span class="p">{</span> <span class="nx">useRef</span><span class="p">,</span><span class="nx">useEffect</span><span class="p">,</span><span class="nx">useState</span> <span class="p">}</span> <span class="nx">from</span> <span class="s1">&#39;react&#39;</span>

<span class="kd">function</span> <span class="nx">App</span><span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="p">{</span>
  <span class="kr">const</span> <span class="p">[</span><span class="nx">count</span><span class="p">,</span> <span class="nx">setCount</span><span class="p">]</span> <span class="o">=</span> <span class="nx">useState</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
  <span class="kd">let</span> <span class="nx">interval</span><span class="p">;</span>
  <span class="nx">useEffect</span><span class="p">(()=&gt;{</span>
    <span class="nx">interval</span> <span class="o">=</span> <span class="nx">setInterval</span><span class="p">(()=&gt;{</span>
      <span class="nx">setCount</span><span class="p">(</span><span class="nx">count</span><span class="o">+</span><span class="mi">1</span><span class="p">)</span>
    <span class="p">},</span><span class="mi">1000</span><span class="p">)</span>
  <span class="p">},[])</span>
  <span class="k">if</span><span class="p">(</span><span class="nx">count</span><span class="o">&gt;</span><span class="mi">5</span><span class="p">){</span>
    <span class="nx">clearInterval</span><span class="p">(</span><span class="nx">interval</span><span class="p">)</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="p">(</span>
    <span class="o">&lt;&gt;</span>
      <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span><span class="p">{</span><span class="nx">count</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/div&gt;</span>
    <span class="o">&lt;</span><span class="err">/&gt;</span>
  <span class="p">)</span>
<span class="p">}</span>

<span class="kr">export</span> <span class="k">default</span> <span class="nx">App</span>
</code></pre></td></tr></table>
</div>
</div><p>当count大于5时，清除定时器，这样写肯定是无效的，因为每次都会创建一个新的interval，clearInterval中的interval并不是最开始的interval，通过useRef改写即可实现：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kr">import</span> <span class="nx">React</span><span class="p">,</span> <span class="p">{</span> <span class="nx">useRef</span><span class="p">,</span><span class="nx">useEffect</span><span class="p">,</span><span class="nx">useState</span> <span class="p">}</span> <span class="nx">from</span> <span class="s1">&#39;react&#39;</span>

<span class="kd">function</span> <span class="nx">App</span><span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="p">{</span>
  <span class="kr">const</span> <span class="p">[</span><span class="nx">count</span><span class="p">,</span> <span class="nx">setCount</span><span class="p">]</span> <span class="o">=</span> <span class="nx">useState</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
  <span class="kd">let</span> <span class="nx">interval</span> <span class="o">=</span> <span class="nx">useRef</span><span class="p">();</span>
  <span class="nx">useEffect</span><span class="p">(()=&gt;{</span>
    <span class="nx">interval</span><span class="p">.</span><span class="nx">current</span> <span class="o">=</span> <span class="nx">setInterval</span><span class="p">(()=&gt;{</span>
      <span class="nx">setCount</span><span class="p">(</span><span class="nx">count</span><span class="o">+</span><span class="mi">1</span><span class="p">)</span>
    <span class="p">},</span><span class="mi">1000</span><span class="p">)</span>
  <span class="p">},[])</span>
  <span class="k">if</span><span class="p">(</span><span class="nx">count</span><span class="o">&gt;</span><span class="mi">5</span><span class="p">){</span>
    <span class="nx">clearInterval</span><span class="p">(</span><span class="nx">interval</span><span class="p">.</span><span class="nx">current</span><span class="p">)</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="p">(</span>
    <span class="o">&lt;&gt;</span>
      <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span><span class="p">{</span><span class="nx">count</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/div&gt;</span>
    <span class="o">&lt;</span><span class="err">/&gt;</span>
  <span class="p">)</span>
<span class="p">}</span>

<span class="kr">export</span> <span class="k">default</span> <span class="nx">App</span>
</code></pre></td></tr></table>
</div>
</div><h3 id="自定义hooks">自定义Hooks</h3>
<p>前面提到类组件有三个缺点，首当其冲的是逻辑复用问题，我们可以通过自定义Hooks来解决该问题，例如我们通过自定义useCount来复用一个定时器：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kr">import</span> <span class="nx">React</span><span class="p">,</span> <span class="p">{</span> <span class="nx">useRef</span><span class="p">,</span> <span class="nx">useEffect</span><span class="p">,</span> <span class="nx">useState</span> <span class="p">}</span> <span class="nx">from</span> <span class="s1">&#39;react&#39;</span>

<span class="kd">function</span> <span class="nx">App</span><span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="p">{</span>
  <span class="kr">const</span> <span class="p">[</span><span class="nx">count</span><span class="p">]</span> <span class="o">=</span> <span class="nx">useCount</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
  <span class="k">return</span> <span class="p">(</span>
    <span class="o">&lt;&gt;</span>
      <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span><span class="p">{</span><span class="nx">count</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/div&gt;</span>
    <span class="o">&lt;</span><span class="err">/&gt;</span>
  <span class="p">)</span>
<span class="p">}</span>

<span class="kd">function</span> <span class="nx">useCount</span><span class="p">(</span><span class="nx">defaultCount</span><span class="p">){</span>
  <span class="kr">const</span> <span class="p">[</span><span class="nx">count</span><span class="p">,</span> <span class="nx">setCount</span><span class="p">]</span> <span class="o">=</span> <span class="nx">useState</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
  <span class="kd">let</span> <span class="nx">interval</span> <span class="o">=</span> <span class="nx">useRef</span><span class="p">();</span>
  <span class="nx">useEffect</span><span class="p">(()</span> <span class="p">=&gt;</span> <span class="p">{</span>
    <span class="nx">interval</span><span class="p">.</span><span class="nx">current</span> <span class="o">=</span> <span class="nx">setInterval</span><span class="p">(()</span> <span class="p">=&gt;</span> <span class="p">{</span>
      <span class="nx">setCount</span><span class="p">(</span><span class="nx">count</span> <span class="p">=&gt;</span> <span class="nx">count</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
    <span class="p">},</span> <span class="mi">1000</span><span class="p">)</span>
  <span class="p">},</span> <span class="p">[])</span>
  <span class="nx">useEffect</span><span class="p">(()=&gt;{</span>
    <span class="k">if</span> <span class="p">(</span><span class="nx">count</span> <span class="o">&gt;=</span> <span class="mi">5</span><span class="p">)</span> <span class="p">{</span>
      <span class="nx">clearInterval</span><span class="p">(</span><span class="nx">interval</span><span class="p">.</span><span class="nx">current</span><span class="p">)</span>
    <span class="p">}</span>
  <span class="p">})</span>
  <span class="k">return</span> <span class="p">[</span><span class="nx">count</span><span class="p">,</span> <span class="nx">setCount</span><span class="p">]</span>
<span class="p">}</span>
<span class="kr">export</span> <span class="k">default</span> <span class="nx">App</span>
</code></pre></td></tr></table>
</div>
</div><p><em><strong>关于React Hooks的优势和常用API使用先写到这，后面的文章再对Hooks的深层实现原理和自定义Hooks学习和解析</strong></em></p>

    </div>

    <div class="post-copyright">
  <p class="copyright-item">
    <span class="item-title">文章作者</span>
    <span class="item-content">smartzheng</span>
  </p>
  <p class="copyright-item">
    <span class="item-title">上次更新</span>
    <span class="item-content">
        2019-08-15
        
    </span>
  </p>
  
  
</div>
<footer class="post-footer">
      <div class="post-tags">
          <a href="/tags/react/">React</a>
          </div>
      <nav class="post-nav">
        <a class="prev" href="/post/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3javascript%E4%B9%8B%E4%BD%9C%E7%94%A8%E5%9F%9F%E9%97%AD%E5%8C%85/">
            <i class="iconfont icon-left"></i>
            <span class="prev-text nav-default">深入理解JavaScript之作用域闭包</span>
            <span class="prev-text nav-mobile">上一篇</span>
          </a>
        <a class="next" href="/post/webpack%E5%AD%A6%E4%B9%A0%E4%B9%8B%E8%BF%9B%E9%98%B6%E7%9F%A5%E8%AF%86%E7%82%B9/">
            <span class="next-text nav-default">webpack学习：进阶知识点</span>
            <span class="next-text nav-mobile">下一篇</span>
            <i class="iconfont icon-right"></i>
          </a>
      </nav>
    </footer>
  </article>
        </div>
        

  

  

      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="social-links">
      <a href="mailto:smartzheng1993@email.com" class="iconfont icon-email" title="email"></a>
      <a href="https://github.com/smartzheng" class="iconfont icon-github" title="github"></a>
      <a href="https://weibo.com/2062336885/profile?topnav=1&amp;wvr=6" class="iconfont icon-weibo" title="weibo"></a>
      <a href="https://www.zhihu.com/people/liu-xia-hui-89-70" class="iconfont icon-zhihu" title="zhihu"></a>
      <a href="https://www.douban.com/people/smartzheng/" class="iconfont icon-douban" title="douban"></a>
  <a href="https://smartzheng.github.io/index.xml" type="application/rss+xml" class="iconfont icon-rss" title="rss"></a>
</div>

<div class="copyright">
  <span class="power-by">
    由 <a class="hexo-link" href="https://gohugo.io">Hugo</a> 强力驱动
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    主题 - 
    <a class="theme-link" href="https://github.com/olOwOlo/hugo-theme-even">Even</a>
  </span>

  

  <span class="copyright-year">
    &copy; 
    2017 - 
    2020
    
  </span>
</div>
    </footer>

    <div class="back-to-top" id="back-to-top">
      <i class="iconfont icon-up"></i>
    </div>
  </div>
  
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/slideout@1.0.1/dist/slideout.min.js" integrity="sha256-t+zJ/g8/KXIJMjSVQdnibt4dlaDxc9zXr/9oNPeWqdg=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.js" integrity="sha256-XVLffZaxoWfGUEbdzuLi7pwaUJv1cecsQJQqGLe7axY=" crossorigin="anonymous"></script>
<script type="text/javascript" src="/dist/even.26188efa.min.js"></script>








</body>
</html>
